import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress' // progress bar
import store from '../store' // progress bar
import constantRoutes from './constantRoutes' // progress bar
import { hasRoute } from '@/utils/index' // progress bar
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })
import { getToken } from '@/utils/auth'


Vue.use(VueRouter)


const router = new VueRouter({
  mode: 'history',
  routes: constantRoutes
})

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = getToken()
  if (hasToken) {
    if (to.path == '/login') {
      next('/')
      NProgress.done()
    } else {
      if (to.path == '/404') return next()
      // 获取用户信息
      try {
        // 获取当前登录用户的信息
        await store.dispatch('user/getUserInfo')
        // 获取菜单
        if (!store.state.permission.sidebarMenuList.length) await store.dispatch('permission/getSidebarMenuList')
        // 获取页面按钮权限
        if (!store.state.permission.perms.length) await store.dispatch('permission/getPerms')

        // 限制用户恶意跳转(鉴权)
        if (hasRoute(to, store.state.permission.sidebarMenuList)) {
          // 路由跳转的同时添加页面标签
          store.commit('addTagList', { name: to.path, title: to.meta.title })
          next()
        } else {
          // 路由权限不足直接跳404 哈哈
          Vue.prototype.$message({
            type: 'warning',
            message: '权限不足,请刷新重试!'
          })
          next('/404')
          NProgress.done()
        }
      } catch (error) {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})




/**
 * 解决路由访问重复时报错问题
 */
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
